﻿using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wt.wine.Application.Common.Interfaces;
using wt.wine.Application.Common.Models;
using wt.wine.Domain.Entities;

namespace wt.wine.Application.ManageConfigtable.Command
{
    public class EditConfigTableRepository : IRequest<Json<string>>
    {
        /// <summary>
        /// 类型：1、确酒提醒配置
        /// </summary>
        public int id { get; set; }
        /// <summary>
        /// 通用预警容量 单位：ml
        /// </summary>
        public int capacitythreshold { get; set; }
    }

    public class EditConfigTableRepositoryHandler : IRequestHandler<EditConfigTableRepository, Json<string>>
    {
        private readonly ICurrentUserService _icurrentUserServices;
        private readonly IConfigtableRepository _iconfigtabelRepository;
        public EditConfigTableRepositoryHandler(ICurrentUserService icurrentUserServices, IConfigtableRepository iconfigtabelRepository)
        {
            _icurrentUserServices = icurrentUserServices;
            _iconfigtabelRepository = iconfigtabelRepository;
        }
        public async Task<Json<string>> Handle(EditConfigTableRepository request, CancellationToken cancellationToken)
        {
            if (request.id <= 0)
            {
                return Json<string>.Failed("请选择需要修改的配置", "");
            }
            else
            {
                int userid = _icurrentUserServices.GetUserId();
                var model = await _iconfigtabelRepository.GetConfigTableById(request.id, userid, cancellationToken);
                if (model != null && model.id
                    > 0)
                {
                    if (model.type == 1 && request.capacitythreshold <= 0)
                    {
                        return Json<string>.Failed("预警容量不能为0", "");
                    }
                    model.capacitythreshold = request.capacitythreshold;
                    model.userid = userid;
                    model.updatetime = DateTime.Now;
                    await _iconfigtabelRepository.EditConfigTable(model, cancellationToken);
                    return Json<string>.Success("修改成功", "");
                }
                else {
                    return Json<string>.Failed("请选择有效的需要修改的配置", "");
                }
            }
        }
    }
}
